package com.codeoss.framework.view.pagebean.base;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.codeoss.framework.context.YunContext;
import com.codeoss.framework.converter.IConverterStore;
import com.codeoss.framework.data.metadata.Column;
import com.codeoss.framework.data.store.ITableStore;
import com.codeoss.framework.expression.Expression;
import com.codeoss.framework.expression.IScriptServiceStore;
import com.codeoss.framework.util.StringUtils;
import com.codeoss.framework.view.component.Formula;
import com.codeoss.framework.view.component.IDataBinding;
import com.codeoss.framework.view.component.Page;
import com.codeoss.framework.view.component.Table;
import com.codeoss.framework.view.component.mobile.MListView;
import com.codeoss.framework.view.service.IVariableService;
import com.codeoss.framework.view.util.PageBeanUtil;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;

@Service
public class BasePageBean {
	@Autowired
	private ITableStore tableStore;
	@Autowired
	private ObjectMapper objectMapper;
	@Autowired
	private IConverterStore converterStore;
	@Autowired
	private IVariableService variableService;
	@Autowired
	private IScriptServiceStore scriptServiceStore;
	@Autowired
	private PageBeanUtil pageBeanUtil;
	public void beforeInit() {

	}

	public void init() {

	}

	public void processComponentValueChangeSystemEvent() {
		YunContext yunContext = YunContext.getCurrentContext();
		String eventSource = yunContext.getViewRequest().getEventSource();
		processComponentValueChangeSystemEvent(eventSource);
	}

	public void processComponentValueChangeSystemEvent(String eventSource) {
		YunContext yunContext = YunContext.getCurrentContext();
		Page page = yunContext.getPage();
		page.findComponentById(yunContext, eventSource);
		List<String> list = page.getDependObject().getDependList(yunContext.getFindComponent().getId());
		List<IDataBinding> dataBindingList = new ArrayList<IDataBinding>();
		for (int i = 0; i < list.size(); i++) {
			page.findComponentById(yunContext, list.get(i));
			IDataBinding dataBinding = (IDataBinding) yunContext.getFindComponent();
			dataBindingList.add(dataBinding);

			if (dataBinding instanceof Formula) {
				Formula formula = (Formula) dataBinding;
				Expression expression = formula.getFormulaExpression();
				Object value = scriptServiceStore.getScriptService(expression).eval(expression.getScript(),
						yunContext.getVarValueMap());
				variableService.setVariableValue(yunContext, formula.getVarName(), value);
			}
		}
		pageBeanUtil.generateFormInfo(dataBindingList);
	}

	protected List<Map<String, Object>> getSubmitData(Table tableComponent, List<IDataBinding> dataBindingList) {
		YunContext yunContext = YunContext.getCurrentContext();
		String sJsonData = yunContext.getViewRequest().getData().get(tableComponent.getId() + "_data");
		com.codeoss.framework.data.metadata.Table table = (com.codeoss.framework.data.metadata.Table) tableStore
				.get(tableComponent.getDataSource());
		List<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>();
		try {
			ArrayNode arrayNode = (ArrayNode) objectMapper.readTree(sJsonData);
			for (int i = 0; i < arrayNode.size(); i++) {
				ObjectNode objectNode = (ObjectNode) arrayNode.get(i);
				Map<String, Object> map = new HashMap<String, Object>();
				dataList.add(map);
				for (int j = 0; j < dataBindingList.size(); j++) {
					IDataBinding dataBinding = dataBindingList.get(j);
					JsonNode jsonNode = objectNode.get(dataBinding.getDataField());
					if (jsonNode != null) {
						String sValue = jsonNode.asText();
						Column column = table.getColumnByColumnName(dataBinding.getDataField());
						Object value = converterStore.getConverter(column.getDataType()).convertStringToObject(sValue);
						map.put(dataBinding.getDataField(), value);
					}
				}
				JsonNode jsonNode = objectNode.get("_recordState_");
				if (jsonNode != null) {
					map.put("_recordState_", jsonNode.asText());
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			throw new RuntimeException(e);
		}
		return dataList;
	}

	protected List<Map<String, Object>> getSubmitData(MListView mListView, List<IDataBinding> dataBindingList) {
		YunContext yunContext = YunContext.getCurrentContext();
		List<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>();

		String sJsonData = yunContext.getViewRequest().getData().get(mListView.getId() + "_data");
		if (!StringUtils.isEmpty(sJsonData)) {
			com.codeoss.framework.data.metadata.Table table = (com.codeoss.framework.data.metadata.Table) tableStore
					.get(mListView.getDataSource());
			try {
				ArrayNode arrayNode = (ArrayNode) objectMapper.readTree(sJsonData);
				for (int i = 0; i < arrayNode.size(); i++) {
					ObjectNode objectNode = (ObjectNode) arrayNode.get(i);
					Map<String, Object> map = new HashMap<String, Object>();
					dataList.add(map);
					for (int j = 0; j < dataBindingList.size(); j++) {
						IDataBinding dataBinding = dataBindingList.get(j);
						JsonNode jsonNode = objectNode.get(dataBinding.getDataField());
						if (jsonNode != null) {
							String sValue = jsonNode.asText();
							if(StringUtils.isEmpty(sValue) || "null".equals(sValue)) {
								map.put(dataBinding.getDataField(), null);
							}else {
								Column column = table.getColumnByColumnName(dataBinding.getDataField());
								Object value = converterStore.getConverter(column.getDataType())
										.convertStringToObject(sValue);
								map.put(dataBinding.getDataField(), value);
							}
							
						}
					}
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				throw new RuntimeException(e);
			}
		}
		return dataList;
	}
}
